package com.jams.goodox.activity.serve;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.mine.settings.InvoiceActivity;
import com.jams.goodox.entity.OrderBillSetBean;
import com.jams.goodox.entity.SellerBillResp;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.InvoiceResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.ChooseBillView;
import com.jams.library.widget.switch_button.SwitchButton;

import butterknife.ButterKnife;
import retrofit2.Call;

import static com.jams.goodox.activity.serve.meet.MeetPartOrderSureActivity.Type_Comment;
import static com.jams.goodox.activity.serve.meet.MeetPartOrderSureActivity.Type_Special;
import static com.jams.goodox.entity.OrderBillSetBean.BillTypeComment;
import static com.jams.goodox.entity.OrderBillSetBean.BillTypeNull;

/**
 * 用于处理发票任务
 * Created by guozhen.hou on 2017/7/17.
 */

public class ChooseBillManager implements View.OnClickListener {
    private SwitchButton switchBtn;
    private LinearLayout checkboxCommentBill;
    private LinearLayout checkboxSpecialBill;
    private ImageView ivSimple;
    private ImageView ivSpecial;
    private RelativeLayout relativeType;
    private TextView txBillCompany;
    private TextView txGoSet;
    private RelativeLayout relative_company;

    private ChooseBillView chooseBillView;

    private ImageView right_arrow_bill;
    private TextView tx_company_bill_hint;

    private Context mContext;
    private String invoiceType = "0";//发票
    private OrderBillSetBean orderBillSetBean;
    private boolean isCompanyOrder;
    private User user;
    private String billCompanyName;

    public ChooseBillManager(Context context, boolean isCompanyOrder, String busId, ChooseBillView view) {
        this.mContext = context;
        if (!(mContext instanceof BaseActivity)) return;
        this.isCompanyOrder = isCompanyOrder;
        this.chooseBillView = view;
        user = DataCacheManager.getInstance().getUser();
        initView(view);
        getBillData(busId);
    }

    private void initView(View activity) {
        chooseBillView.setVisibility(View.GONE);//默认不显示发票信息
        switchBtn = ButterKnife.findById(activity, R.id.switchBtn_bill);
        checkboxCommentBill = ButterKnife.findById(activity, R.id.lv_simple_group);
        checkboxSpecialBill = ButterKnife.findById(activity, R.id.lv_special_group);
        ivSimple = ButterKnife.findById(activity, R.id.iv_simple_bill);
        ivSpecial = ButterKnife.findById(activity, R.id.iv_special_bill);
        relativeType = ButterKnife.findById(activity, R.id.relative_type_bill);
        txBillCompany = ButterKnife.findById(activity, R.id.tx_bill_company);
        txGoSet = ButterKnife.findById(activity, R.id.tx_goSet_bill);
        relative_company = ButterKnife.findById(activity, R.id.relative_company_bill);

        right_arrow_bill = ButterKnife.findById(activity, R.id.right_arrow_bill);
        tx_company_bill_hint = ButterKnife.findById(activity, R.id.tx_company_bill_hint);

        checkboxCommentBill.setOnClickListener(this);
        checkboxSpecialBill.setOnClickListener(this);
        relative_company.setOnClickListener(this);

        switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (switchBtn.isChecked()) {
                    if (isCompanyOrder && TextUtils.isEmpty(billCompanyName)) {
                        tx_company_bill_hint.setVisibility(View.VISIBLE);
                        relativeType.setVisibility(View.GONE);
                        relative_company.setVisibility(View.GONE);
                    } else {
                        relativeType.setVisibility(View.VISIBLE);
                        relative_company.setVisibility(View.VISIBLE);
                    }
                } else {
                    tx_company_bill_hint.setVisibility(View.GONE);
                    relativeType.setVisibility(View.GONE);
                    relative_company.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 获取发票信息
     */
    private void getBillData(String busId) {
        invoiceType = "0";//防止刷新数据时，此处记录之前标识
        if (TextUtils.isEmpty(busId)) return;
        orderBillSetBean = new OrderBillSetBean();
        ((BaseActivity) mContext).enqueue(((BaseActivity) mContext).createCallService(ServiceService.class).getSellerBillMsg(busId), new RetrofitCallbackListener<SellerBillResp>() {
            @Override
            public void onSuccess(Call<SellerBillResp> call, SellerBillResp result) {
                if (result.getData() == null) return;
                orderBillSetBean.setOpenBillType(result.getData().getOpenBillType());
                //如果不允许开设发票，直接结束发票逻辑
                if (!result.getData().hasBill()) {
                    chooseBillView.setVisibility(View.GONE);
                    return;
                }
                getMyInvoice();//产品原型修改，坑
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 获取发票抬头设置
     */
    public void getMyInvoice() {
        ((BaseActivity) mContext).enqueue(((BaseActivity) mContext).createCallService(EnterpriseService.class).myInvoice(isCompanyOrder ? user.getEnterpriseAdminId() : ""), new RetrofitCallbackListener<InvoiceResp>() {
            @Override
            public void onSuccess(Call<InvoiceResp> call, InvoiceResp result) {
                if (result.data != null) {
                    orderBillSetBean.setCommentBillCompanyName(result.data.enterpriseNameNormal);
                    orderBillSetBean.setSpecialBillCompanyName(result.data.enterpriseNameSpecial);
                }
                setBillData();
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 此处设置发票栏目显示:由于可能是重设发票抬头，重新获取发票信息。此处需要根据本地选择的发票抬头类型设置界面
     * 0：不允许设置发票：判断逻辑在获取发票信息中
     * 1：普通发票
     * 2：增值税发票
     * 3：两种都可以开
     */
    private void setBillData() {
        switch (orderBillSetBean.getOpenBillType()) {
            case BillTypeNull:
                chooseBillView.setVisibility(View.GONE);
                break;
            case BillTypeComment:
                chooseBillView.setVisibility(View.VISIBLE);
                checkboxSpecialBill.setVisibility(View.GONE);
                checkboxCommentBill.setVisibility(View.VISIBLE);
                ivSimple.setImageResource(R.mipmap.ols_comment_checkbox_checked);
                billCompanyName = orderBillSetBean.getCommentBillCompanyName();
                invoiceType = Type_Comment;
                break;
            case OrderBillSetBean.BillTypeSpecial:
                chooseBillView.setVisibility(View.VISIBLE);
                checkboxCommentBill.setVisibility(View.GONE);
                checkboxSpecialBill.setVisibility(View.VISIBLE);
                ivSpecial.setImageResource(R.mipmap.ols_comment_checkbox_checked);
                billCompanyName = orderBillSetBean.getSpecialBillCompanyName();
                invoiceType = Type_Special;
                break;
            case OrderBillSetBean.BillTypeAll:
                if (isSetInVoiceType()) {//此处仅重新获取当前发票抬头即可
                    billCompanyName = BillTypeComment.equalsIgnoreCase(invoiceType) ?
                            orderBillSetBean.getCommentBillCompanyName() : orderBillSetBean.getSpecialBillCompanyName();
                } else {
                    chooseBillView.setVisibility(View.VISIBLE);
                    checkboxCommentBill.setVisibility(View.VISIBLE);
                    checkboxSpecialBill.setVisibility(View.VISIBLE);
                    ivSimple.setImageResource(R.mipmap.ols_comment_checkbox_checked);
                    ivSpecial.setImageResource(R.mipmap.ols_comment_checkbox_normal);
                    billCompanyName = orderBillSetBean.getCommentBillCompanyName();
                    invoiceType = Type_Comment;
                }
                break;
        }
        setBillCompanyName();
    }

    /**
     * 是否设置发票类型
     * 1：初次进入为0，根据后台返回对象设置界面显示
     * 2：选择or默认设置完，再次修改发票设置，使用选择后的invoice类型，所以需要判断是否存在是否有设置invoiceType
     */
    private boolean isSetInVoiceType() {
        return !(TextUtils.isEmpty(invoiceType) || invoiceType.equalsIgnoreCase(BillTypeNull));
    }

    /**
     * 设置发票公司栏信息
     * 1：如果是企业订单，不可修改，右侧箭头隐藏;如果是未设置对应的发票，此处显示为设置提示，同时类型，发票抬头隐藏
     * 2：个人账号 可修改，右侧箭头显示；且开票公司抬头可能为空，此时显示提示文案等
     */
    private void setBillCompanyName() {
        if (isCompanyOrder) {
            if (TextUtils.isEmpty(billCompanyName)) {
                invoiceType = "0";
            } else {
                txBillCompany.setText(billCompanyName);
            }
            txGoSet.setVisibility(View.GONE);
            relative_company.setEnabled(false);
            right_arrow_bill.setVisibility(View.GONE);
        } else {
            relative_company.setEnabled(true);
            right_arrow_bill.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(billCompanyName)) {
                txBillCompany.setText("");
                txGoSet.setVisibility(View.VISIBLE);
            } else {
                txBillCompany.setText(billCompanyName);
                txGoSet.setVisibility(View.GONE);
            }
        }
    }

    public String getInvoiceType() {
        if (TextUtils.isEmpty(billCompanyName) || !switchBtn.isChecked()) invoiceType = "0";
        return invoiceType == null ? "0" : invoiceType;
    }

    /**
     * 获取发票抬头
     *
     * @return 发票抬头
     */
    public String getInvoiceName() {
        return billCompanyName == null ? "" : billCompanyName;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lv_simple_group:
                ivSimple.setImageResource(R.mipmap.ols_comment_checkbox_checked);
                ivSpecial.setImageResource(R.mipmap.ols_comment_checkbox_normal);
                billCompanyName = orderBillSetBean.getCommentBillCompanyName();
                setBillCompanyName();
                invoiceType = Type_Comment;
                break;
            case R.id.lv_special_group:
                ivSimple.setImageResource(R.mipmap.ols_comment_checkbox_normal);
                ivSpecial.setImageResource(R.mipmap.ols_comment_checkbox_checked);
                billCompanyName = orderBillSetBean.getSpecialBillCompanyName();
                setBillCompanyName();
                invoiceType = Type_Special;
                break;
            case R.id.relative_company_bill:
                Intent intent1 = new Intent(mContext, InvoiceActivity.class);
                ((Activity) mContext).startActivityForResult(intent1, 1991);
                break;
        }
    }
}
